//go:build darwin || linux || freebsd || openbsd
// +build darwin linux freebsd openbsd

package lockfile

import (
	"errors"
	"os"
	"syscall"
)

var ErrWouldBlock = errors.New("lock file temporarily unavailable")

func lockFile(f *os.File, block bool) error {
	how := syscall.LOCK_EX
	if !block {
		how |= syscall.LOCK_NB
	}

	err := syscall.Flock(int(f.Fd()), how)
	if err == syscall.EWOULDBLOCK {
		err = ErrWouldBlock
	}

	return err
}

func unlockFile(f *os.File) error {
	err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
	if err == syscall.EWOULDBLOCK {
		err = ErrWouldBlock
	}
	return err
}
